package com.jxd.dianping.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jxd.dianping.common.*;
import com.jxd.dianping.model.CategoryModel;
import com.jxd.dianping.request.CategoryReq;
import com.jxd.dianping.request.PageQuery;
import com.jxd.dianping.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;

@Controller("/admin/category")
@RequestMapping("/admin/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    // 获取商户列表
    @RequestMapping("/index")
    @AdminPermission
    public ModelAndView index(PageQuery pageQuery) {
        // 设置从第几页开始一页查多少个
        PageHelper.startPage(pageQuery.getPage(), pageQuery.getSize());
        List<CategoryModel> categoryModels = categoryService.selectAll();
        // pages 总页数
        // total 总条数
        PageInfo<CategoryModel> sellerModelPageInfo = new PageInfo<>(categoryModels);
        ModelAndView modelAndView = new ModelAndView("/admin/category/index.html");
        modelAndView.addObject("data", sellerModelPageInfo);
        modelAndView.addObject("CONTROLLER_NAME","category");
        modelAndView.addObject("ACTION_NAME","index");
        return modelAndView;
    }

    // 跳转到创建页
    @RequestMapping("/createPage")
    @AdminPermission
    public ModelAndView createPage() {
        ModelAndView modelAndView = new ModelAndView("/admin/category/create.html");
        modelAndView.addObject("CONTROLLER_NAME","category");
        modelAndView.addObject("ACTION_NAME","create");
        return modelAndView;
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    // 不能加@RequestBody的1原因
    // 加上RequestBody 就必须以Json view的方式去解析 已Json的方式去处理请求 ajax json post进行处理
    // 不加上 是以Form的方式去解析处理 key - value & key - value 的形式
    public String create(@Valid CategoryReq createCategory, BindingResult bindingResult) throws BusinessException {
        if (bindingResult.hasErrors()) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, CommonUtil.processErrorString(bindingResult));
        }
        CategoryModel categoryModel = new CategoryModel();
        categoryModel.setName(createCategory.getName());
        categoryModel.setIconUrl(createCategory.getIconUrl());
        categoryModel.setSort(createCategory.getSort());
        categoryService.create(categoryModel);
        return "redirect:/admin/category/index.html";
    }
}
